import $http from '../api/service/getData'
import account from './account.js'

const IS_PROD = process.env.NODE_ENV === 'production'
const $ls = window.localStorage

export default function () {
  // TODO: 模拟登录打开
  let isOpen = true
  if (IS_PROD && !isOpen) {
    return Promise.resolve()
  } else {
    const JSEncrypt = require('jsencrypt').default
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(SYSTEM_MANAGE_VUE_CONFIG.RSA_PUBLICKEY)
    return $http.post('login', {
      username: account.username,
      password: encrypt.encrypt(account.password)
    })
      .then(res => {
        let data = res.data
        if (data.resultCode === 0) {
          $ls.setItem('token', data.access_token)
          $ls.setItem('username', account.username)
          return $http.get('userInfo')
        } else {
          return Promise.reject(new Error(data.action_message))
        }
      })
      .then(res => {
        let data = res.data
        let info = data.data
        if (data.resultCode === 0) {
          setUserStorage(info)
        }
      })
      .catch(error => {
        console.error(error)
      })
  }
}

const setUserStorage = info => {
  $ls.setItem('userInfo.outerReqFlag', info.outerReqFlag)
  $ls.setItem('userInfo.logId', info.logId)
  $ls.setItem('userInfo.userId', info.userId)
  $ls.setItem('userInfo.userName', info.userName)
  $ls.setItem('userInfo.ip', info.ip)
  $ls.setItem('userInfo.orgName', info.orgName)
  $ls.setItem('userInfo.orgId', info.orgId)
  $ls.setItem('userInfo.orgCode', info.orgCode)
  $ls.setItem('userInfo.orgType', info.orgType)
  $ls.setItem('userInfo.corpId', info.corpId)
  $ls.setItem('userInfo.corpCode', info.corpCode)
  $ls.setItem('userInfo.corpName', info.corpName)
  $ls.setItem('userInfo.corpType', info.corpType)
  $ls.setItem('userInfo.staffName', info.staffName)
  $ls.setItem('userInfo.staffId', info.staffId)
}
